use js_sys::Date;
use wasm_bindgen::prelude::*;

fn console_log(message: String) {
    web_sys::console::log_1(&message.into());
}

#[wasm_bindgen]
pub fn add(a: i32, b: i32) -> i32 {
    let sum = 100000000;
    return a + b + sum;
}

#[wasm_bindgen]
pub fn update_message(selector: &str, message: &str) {
    let window = web_sys::window().expect("Failed to load window");
    let document = window.document().expect("Failed to load document");
    let element = document
        .query_selector(selector)
        .expect("Failed to load element");

    if let Some(element) = element {
        element.set_inner_html(message);
    } else {
        panic!("Failed to set inner html")
    }
}

#[wasm_bindgen]
pub fn print_values(
    js_number: i32,
    js_number2: i32,
    js_boolean: bool,
    js_uint8_array: &[u8],
    js_number_array: Vec<i32>,
) {
    console_log(format!("js number: {}", js_number));
    console_log(format!("js number: {}", js_number2));
    console_log(format!("js boolean: {}", js_boolean));

    for x in js_number..js_number2 {
        console_log(format!("value is {}", x));
    }

    for item in js_uint8_array {
        console_log(format!("js Uint8Array item: {}", item));
    }

    for item in js_number_array {
        console_log(format!("js number array item: {}", item));
    }
}

//Rust中提供了一个通用的类型——JsValue，可以作为任何JS类型
#[wasm_bindgen]
pub fn print_js_value(val: JsValue) {
    console_log(format!("{:?}", val));
}

//使用Result返回报错
#[wasm_bindgen]
pub fn only_return_error_when_result(count: i32) -> Result<(), JsError> {
    if count > 10 {
        Ok(()) //返回为空
    } else {
        Err(JsError::new("count < 10"))
    }
}

//使用Result返回正常值和错误
#[wasm_bindgen]
pub fn return_all_when_result(count: i32) -> Result<i32, JsError> {
    if count > 10 {
        Ok(count + 10)
    } else {
        Err(JsError::new("count < 10"))
    }
}

#[wasm_bindgen]
pub fn return_time() -> f64 {
    let date = Date::new_0();
    date.get_time()
}

//
#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen(js_namespace = console)]
    fn log(message: &str); //如果不指定js_name ，则函数名称必须和js_namespace下的方法名称相同

    #[wasm_bindgen(js_namespace = console, js_name = log)]
    fn log_str(message: &str);
}

//rust调用js中的函数
#[wasm_bindgen(raw_module = "../pages/index.js")]
extern "C" {
    fn addIt(m: i32, n: i32) -> i32;
}

#[wasm_bindgen]
pub fn call_js_func() {
    log("hello, javascript!");
    log_str("hello, javascript!");
    addIt(1, 2); //rust调用js中的函数
}

// JS调用Rust的struct
#[wasm_bindgen]
pub struct User {
    name: String,
    age: u32,
}

#[wasm_bindgen]
impl User {
    #[wasm_bindgen(constructor)]
    pub fn new(name: String, age: u32) -> User {
        User { name, age }
    }

    pub fn print_user(&self) {
        log(format!("name is : {}, age is : {}", self.name, self.age).as_str());
    }

    pub fn set_age(&mut self, age: u32) {
        self.age = age;
    }
}
